package tree;

import java.util.Arrays;

/**
 * @Author leecho
 * @Date: 2021/10/26 11:17
 * @Version 1.0
 */

public class HeapSort {
    public static void main(String[] args) {
        int[] arr ={2,232,1,21,44,0};
        heapSort(arr);
        System.out.println(Arrays.toString(arr));

    }

    public static void heapSort(int[] arr){
        int temp = 0;
        for (int i = arr.length/2 - 1; i >= 0; i--) {
            adjustHeap(arr,i,arr.length);
        }

//        for (int i = arr.length - 1; i > 0; i--) {
//            temp = arr[i];
//            arr[i] = arr[0];
//            arr[0] = temp;
//            adjustHeap(arr,0,i);
//        }
    }

    public static void adjustHeap(int[] arr, int i, int length){
        int temp = arr[i];

        // j = i*2 + 1 i的左结点
        // arr[j] < arr[j+1] 左结点和有结点比较
        // 大的值和父结点交换
        for (int j = i*2 + 1; j < length; j = j *2 + 1) {
            if (j+1 < length && arr[j] < arr[j+1]){
                j++;
            }
            if (temp < arr[j]){
                arr[i] = arr[j];
                i = j;
            } else {
                break;
            }
        }
        // 如果左右结点没有比父节点大还是原值
        arr[i] = temp;
    }
}
